package com.itheima.reggie.controller;

import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController       //@ResponseBody + @Controller
public class EmployeeController {

    //依赖注入service层
    @Autowired
    private EmployeeService employeeService;

    //登录功能
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> param, HttpSession session) {
        //1.获取前端传来的参数
        String username = param.get("username");
        String password = param.get("password");
        //2.调用service层
        ResultInfo resultInfo = employeeService.login(username, password);
        //3.判断从service返回的数据
        if (resultInfo.getCode() == 1) {
            //若返回成功,则存入session域
            session.setAttribute(Constant.SESSION_EMPLOYEE, resultInfo.getData());   //使用常量类避免了字符串的耦合性影响
        }

        //4.返回结果
        return resultInfo;

    }


    //员工注销登录
    @PostMapping("/employee/logout")
    public ResultInfo logout(HttpSession session){
        //1.清空session域内容
        session.invalidate();
        //2.向前端发送响应
        return ResultInfo.success();
    }


    //查询员工列表
    @GetMapping("/employee/find")
    public ResultInfo findList(String name){
        //1.调用service层代码
        List<Employee> list = employeeService.findList(name);

        //2.封装到ResultInfo,并返回响应
        return ResultInfo.success(list);
    }

    //添加员工信息
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){     //接收请求体中的参数
        //1.调用service层
        employeeService.save(employee);
        //2.返回响应
        return ResultInfo.success();
    }

    //回显员工信息
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable Long id){      //接收请求头中以路径形式传递的参数
        //1.调用service层
        Employee employee = employeeService.findById(id);
        //2.将数据封装到ResultInfo中,并返回响应
        return ResultInfo.success(employee);
    }

    //修改员工信息 + 设置状态码
    @PutMapping("/employee")
    public ResultInfo updateById(@RequestBody Employee employee){       //接收请求体重的参数
        //1.调用service层
        employeeService.updateById(employee);

        //2.返回响应
        return ResultInfo.success();
    }
}
